package org.example.diet_compass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.example.diet_compass.domain.Goods;
import org.example.diet_compass.domain.Orders;
import org.example.diet_compass.dto.OrderListResultDto;
import org.example.diet_compass.dto.OrderGoodDto;
import org.example.diet_compass.dto.OrdersDto;
import org.example.diet_compass.mapper.GoodsMapper;
import org.example.diet_compass.mapper.OrderItemsMapper;
import org.example.diet_compass.mapper.OrdersMapper;
import org.example.diet_compass.service.OrdersService;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
* @author 86135
* @description 针对表【orders(存储订单信息的表)】的数据库操作Service实现
* @createDate 2025-03-16 11:01:05
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService {

    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private OrderItemsMapper orderItemsMapper;

    @Override
    public int getUserIdByOrderId(Integer orderId) {
        return ordersMapper.getUserIdByOrderId(orderId);
    }

    @Transactional
    @Override
    public OrdersDto getOrderDetailByUserIdAndOrderId(Integer userId, Integer orderId) {
        List<String> goodIds = orderItemsMapper.getGoodIdsByOrderId(orderId);
        List<Goods> goodsByIds = goodsMapper.getGoodsByIds(goodIds);
        ArrayList<OrderGoodDto> orderGoodDtos = new ArrayList<>();
        goodsByIds.forEach(good -> {
            OrderGoodDto orderGoodDto = new OrderGoodDto();
            ModelMapper modelMapper = new ModelMapper();
            modelMapper.map(good, orderGoodDto);
            Double price = goodsMapper.getGoodPriceById(good.getId());
            orderGoodDto.setPrice(price);
            Integer count = orderItemsMapper.getGoodCountByOrderIdAndGoodId(orderId, good.getId());
            orderGoodDto.setQuantity(count);
            orderGoodDtos.add(orderGoodDto);
        });
        Orders order = ordersMapper.selectById(orderId);
        OrdersDto ordersDto = new OrdersDto();
        ordersDto.setSkus(orderGoodDtos);
        ordersDto.setId(orderId);
        String format = order.getOrderDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        ordersDto.setCreateTime(format);
        ordersDto.setTotalMoney(order.getTotalAmount());
        ordersDto.setPayMoney(order.getTotalAmount());
        ordersDto.setTotalNum(orderItemsMapper.getOrderTotalCount(orderId));
        return ordersDto;
    }

    @Override
    @Transactional
    public OrderListResultDto getOrdersByPage(int currentPage, int pageSize, Integer userId, String status) {

        //二级列表
        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();
        //顶级对象
        OrderListResultDto orderListResultDto = new OrderListResultDto();
        //分页查询
        Page<Orders> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("status", status);
        queryWrapper.orderByDesc("order_date");
        Page<Orders> ordersPage = ordersMapper.selectPage(page, queryWrapper);
        if (ordersPage.getRecords().isEmpty()) {
            return null;}
        List<Orders> records = ordersPage.getRecords();
        //利用分页得到的order记录，循环获取id。
        records.forEach(ordersRow -> {
            //orderRecordDto数组保存每个订单的商品信息-三级列表
            ArrayList<OrderGoodDto> orderGoodDtos = new ArrayList<>();
            //二级列表ordersDtos对象创建
            Integer orderId = ordersRow.getOrderId();
            OrdersDto ordersDto = new OrdersDto();
            ordersDto.setOrderState(status);
            LocalDateTime orderDate = ordersRow.getOrderDate();
            String format = orderDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            ordersDto.setCreateTime(format);
            ordersDto.setId(orderId);
            ordersDto.setTotalMoney(ordersRow.getTotalAmount());
            ordersDto.setPayMoney(ordersRow.getTotalAmount());
            //商品总件数
            int totalNum =  orderItemsMapper.getOrderTotalCount(orderId);
            ordersDto.setTotalNum(totalNum);
            //根据orderId来获取本次订单包含的商品id
            List<String> goodIds = orderItemsMapper.getGoodIdsByOrderId(orderId);
            List<Goods> goodsByIds = goodsMapper.getGoodsByIds(goodIds);
            //根据goodId再获取商品信息
            goodsByIds.forEach(good -> {
                //将商品的部分信息映射到orderRecordDto中
                ModelMapper modelMapper = new ModelMapper();
                OrderGoodDto orderGoodDto = new OrderGoodDto();
                modelMapper.map(good, orderGoodDto);
                //根据商品id和订单id获取购买的数量
                Integer count = orderItemsMapper.getGoodCountByOrderIdAndGoodId(orderId, good.getId());
                //更新orderRecordDto里的购买数量
                orderGoodDto.setQuantity(count);
                //添加到数组中
                orderGoodDtos.add(orderGoodDto);
            });
            //三级列表添加到二级列表的对象里
            ordersDto.setSkus(orderGoodDtos);
            //二级列表数组添加
           ordersDtos.add(ordersDto);
        });
        //一级列表的封装
        orderListResultDto.setItems(ordersDtos);
        orderListResultDto.setPages(page.getPages());
        orderListResultDto.setCurrentPage(page.getCurrent());
        orderListResultDto.setPageSize(page.getSize());
        orderListResultDto.setCounts(page.getTotal());

        return orderListResultDto;
    }

    @Override
    public void updateOrderState(Integer orderId, String status) {
        ordersMapper.updateOrderState(orderId, status);
    }

    @Override
    public Integer getOrderIdByUserIdAndState(int userId, String state) {
        return ordersMapper.getOrderId(userId, state).get(0);
    }

}




